﻿using LuShanTea.Admin.Web.Controllers;
using LuShanTea.DTO;
using LuShanTea.IService;
using LuShanTea.Web.Common;
using System.Web.Mvc;

namespace LuShanTea.Admin.Web.App_Start
{
    public class AuthorizeFilter : IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            CheckPermissionAttribute[] attributes = (CheckPermissionAttribute[])filterContext.ActionDescriptor.GetCustomAttributes(typeof(CheckPermissionAttribute), false);

            if (attributes.Length <= 0)
            {
                return;
            }



            if (filterContext.HttpContext.Session["ADMINID"] == null)
            {
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    filterContext.Result = new JsonNetResult
                    {
                        Data = new AjaxResult { Status = "redirect", ErrorMsg = "你还没有登录!", Data = "/AdminLogin/Login" }

                    };

                    return;
                }
                filterContext.Result = new RedirectResult("/AdminLogin/Index");
                return;
            }

            long id = (long)filterContext.HttpContext.Session["ADMINID"];

            IAdminUserService adminUser = DependencyResolver.Current.GetService<IAdminUserService>();

            foreach (var attr in attributes)
            {
                if (!adminUser.HasPermission(id, attr.Permission))
                {
                    if (filterContext.HttpContext.Request.IsAjaxRequest())
                    {
                        filterContext.Result = new JsonNetResult
                        {
                            Data = new AjaxResult { Status = "error", ErrorMsg = "你没有" + attr.Permission + "权限" }

                        };

                        return;
                    }
                    filterContext.Result = new ContentResult { Content = "你没有" + attr.Permission + "的权限" };
                    return;
                }
            }
            ILogService logSer = DependencyResolver.Current.GetService<ILogService>();
            LogDTO dto = new LogDTO();
            dto.AdminUserId = (long)filterContext.HttpContext.Session["ADMINID"];
            dto.Describle = "请求" + filterContext.Controller + "下的" + filterContext.ActionDescriptor.ActionName;
            logSer.AddNew(dto);
        }
    }
}